<template>
	<div class="form">
		<van-form :readonly="isView" :show-error="!isView" :show-error-message="!isView" ref="form">
			<van-field v-model="title" name="标题" label="标题" placeholder="标题" :rules="[
          { required: true, message: '请填写文章标题', trigger: 'onBlur' },
        ]" />
			<van-field v-model="abstract" name="摘要" label="摘要" placeholder="摘要" />
			<van-field v-model="author" name="作者" label="作者" placeholder="作者" :rules="[
          { required: true, message: '请填写文章作者', trigger: 'onBlur' },
        ]" />
			<van-field v-model="origin" name="来源" label="来源" placeholder="来源" />
			<van-field name="内容" label="内容" type="text" id="editor">
			</van-field>
			<div class="quillBox">
				<quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)"
					@focus="onEditorFocus($event)" @ready="onEditorReady($event)" style="height: 300px;"
					:class="isView ? 'view' : ''">
				</quill-editor>
				<div class="ruleBox" @click="quillFn"></div>
			</div>
			<van-field name="缩略图" label="缩略图" :rules="[{ validator: validateThumbnail, message: '请上传缩略图' }]">
				<template #input>
					<van-image v-if="isView" width="80" height="80" :src="thumbnail" />
					<van-uploader v-else v-model="thumbnailList" :multiple="false" :max-count="1" accept="image/*" />
				</template>
			</van-field>

			<van-field name="附件" label="附件">
				<template #input>
					<div v-if="isView">
						<van-image v-for="item in attachment" :key="item.id" width="80" height="80" :src="item.url"
							style="margin-right: 10px" />
					</div>
					<van-uploader v-else v-model="attachmentFileList" :multiple="true" :max-count="10" />
				</template>
			</van-field>
			<div style="margin: 16px">
				<van-button v-if="isView" round block type="info" native-type="button" @click="changeEdit">编辑
				</van-button>
				<van-button v-else round block type="info" native-type="button" @click="onSubmit">提交</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
	import {
		mediaURL,
		uploadURL
	} from "@/api/base.js";
	import axios from "axios";
	import CryptoJS from "crypto-js";
	import params from "@/api/prod.js";
	import {
		Toast
	} from "vant";

	import "quill/dist/quill.core.css";
	import "quill/dist/quill.snow.css";
	import "quill/dist/quill.bubble.css";
	import {
		quillEditor
	} from "vue-quill-editor";
	import Quill from "quill";

	// var container = document.getElementById("editor");
	// var editor = new Quill(container);
	export default {
		components: {
			quillEditor,
		},
		data() {
			return {
				id: "", // 文章id
				username: "",
				userID: "", // 融媒体系统用户ID
				title: "", //标题
				abstract: "", //摘要
				author: "", //作者
				origin: "", // 来源
				content: "", //文章内容
				attachment: [], // 附件
				attachmentFileList: [], // 附件上传列表
				thumbnail: "", //文章缩略图
				thumbnailList: [], //缩略图上传列表
				thirdAccounts: "", //第三方账号平台ID
				rules: {},
				type: "",
				word: "<h2>I am Example</h2><p>富文本富文本</p>",
			};
		},
		computed: {
			editorOption() {
				return {
					placeholder: "请在这里输入",
					modules: {
						toolbar: [
							["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
							[{
								header: 1
							}, {
								header: 2
							}], // 标题，键值对的形式；1、2表示字体大小
							[{
								list: "ordered"
							}, {
								list: "bullet"
							}], //列表
							[{
								script: "sub"
							}, {
								script: "super"
							}], // 上下标
							[{
								indent: "-1"
							}, {
								indent: "+1"
							}], // 缩进
							[{
								size: ["small", false, "large", "huge"]
							}], // 字体大小
							[{
								header: [1, 2, 3, 4, 5, 6, false]
							}], //几级标题
							[{
								align: []
							}], //对齐方式
							["clean"], //清除字体样式
						],
					},
				};
			},
			isView() {
				return this.type === "view";
			},

			isEdit() {
				return this.type === "edit";
			},
		},
		mounted() {
			this.getURLParams();
			this.getToken();
			this.getOauth();
			if (this.type !== "add") {
				this.getArticleData();
			}
		},
		methods: {
			changeEdit() {
				this.type = "edit";
				this.$nextTick(() => {
					this.$refs.form.resetValidation();
				});
			},
			getURLParams() {
				const searchParmas = new URLSearchParams(location.search);
				// this.username = searchParmas.get("username") || "PAPbj_admin2";
				// this.id = searchParmas.get("articleId") || "20210901_16_19";
				// this.type = searchParmas.get("type") || "view";

				this.username = searchParmas.get("username") || "PAPbj_admin3";
				this.id = searchParmas.get("articleId") || "20210826_16_8";
				this.type = searchParmas.get("type") || "view";
			},
			getArticleData() {
				// 获取当前10位的时间戳
				const timestamp = Math.round(new Date().getTime() / 1000).toString();
				// secret + 10位时间戳的前六位，然后进行两次MD5加密
				const sign = CryptoJS.MD5(
					CryptoJS.MD5(params.secret + timestamp.slice(0, 6)).toString()
				).toString();

				const url =
					`${mediaURL}/api/open/wujing/article-info?timestamp=${timestamp}&sign=${sign}&from=${params.from}&companyId=${params.companyId}&uuid=${this.id}`;
				return this.$http.get(url).then((res) => {
					const data = res.data;
					console.log(data, "data");
					this.title = data.title;
					this.abstract = data.abstract;
					this.author = data.author;
					this.origin = data.origin;
					this.content = data.content;
					this.thumbnail = data.thumbnail;
					this.attachment = data.attachment || [];

					this.thumbnailList = [{
						name: this.thumbnail.split("/")[
							this.thumbnail.split("/").length - 1
						],
						url: this.thumbnail,
					}, ];

					this.attachmentFileList = [...this.attachment];
				});
			},
			getOauth() {
				const url = `${mediaURL}/api/open/wujing/oauth-list`;
				const postData = {
					page: 1,
					limit: 15,
				};
				return this.$http.post(url, postData).then((res) => {
					const list = res?.data?.list;
					this.thirdAccounts = list.map((item) => item.value).join(",");
				});
			},
			validateThumbnail() {
				console.log(111);
				if (this.thumbnailList.length > 0) return true;
				else return false;
			},
			async getPolicy() {
				const url = `${mediaURL}/api/open/wujing/get-policy`;
				return this.$http({
					method: "post",
					url,
					headers: {
						Authorization: this.token
					},
				}).then((res) => {
					const {
						data
					} = res;
					return data;
				});
			},
			handleAfterRead(file) {
				const {
					size,
					name
				} = file;
				const ext = name.split(".")[name.split(".").length - 1];
				const data = {
					size,
					ext,
					type: "img",
				};
			},
			getToken() {
				const url = `${mediaURL}/api/open/wujing/user-login`;
				const data = {
					username: this.username,
				};

				return this.$http.post(url, data).then((res) => {
					this.token = res.data.token || "";
				});
			},
			checkStorageSpace(data) {
				const url = `${mediaURL}/api/open/wujing/before-upload`;
				return this.$http({
					method: "post",
					url,
					data,
					headers: {
						Authorization: this.token
					},
				}).then((res) => {
					const {
						code
					} = res;
					return code;
				});
			},

			onSubmit() {
				this.$refs.form
					.validate()
					.then(async () => {
						if (this.content == '') {
							Toast('请填写内容')
							return
						}

						// 校验存储空间
						const thumbnailCheckResult = await this.checkStorageResult(
							this.thumbnailList
						);
						const attachmentCheckResult = await this.checkStorageResult(
							this.attachmentFileList
						);
						if (!thumbnailCheckResult || !attachmentCheckResult) {
							Toast("存储空间不足");
							return;
						}

						// 获取验签参数
						const policyData = await this.getPolicy();
						const {
							host,
							dir
						} = policyData;

						// 上传文件
						this.handleBatchUpload(this.thumbnailList, policyData);
						this.handleBatchUpload(this.attachmentFileList, policyData);

						// 如果有url直接用url，没有url属性代表是新上传的文件，用file对象的name属性进行拼接
						const thumbnailUrl =
							this.thumbnailList[0].url ||
							host + "/" + dir + this.thumbnailList[0]?.file?.name;

						const orgainAttachment = this.attachmentFileList.filter(
							(item) => !!item.url
						);
						const newAttachment = this.attachmentFileList.filter(
							(item) => !!item.file
						);
						const attachment = [
							...orgainAttachment,
							...newAttachment.map((item) => ({
								name: item.file.name,
								url: host + "/" + dir + item.file.name,
							})),
						];

						const postData = {
							username: this.username,
							title: this.title,
							abstract: this.abstract,
							author: this.author,
							origin: this.origin,
							content: this.content,
							thumbnail: thumbnailUrl,
							attachment,
							thirdAccounts: this.thirdAccounts,
						};
						if (this.isEdit) postData.uuid = this.id;

						const url = this.isEdit ?
							`${mediaURL}/api/open/wujing/article-update` :
							`${mediaURL}/api/open/wujing/article-create`;
						return this.$http.post(url, postData).then((res) => {
							console.log(res, "res11111111");
							const success = res.code === 10000;
							Toast({
								type: success ? "success" : "fail",
								message: res.msg,
							});
						});
					})
					.catch((err) => {
						console.log(err, "err");
					})
					.finally(() => {
						//内容
						if (this.content == '') return
					})
			},

			// 上传文件
			async uploadFile(data) {
				const url = data.url;
				const http = axios.create({
					baseURL: "",
					headers: {
						"Content-Type": "multipart/form-data;charset=UTF-8",
					},
				});

				const postData = new FormData();
				postData.append("name", data.name);
				postData.append("key", data.dir + "${filename}");
				postData.append("policy", data.policy);
				postData.append("OSSAccessKeyId", data.accessid);
				postData.append("success_action_status", 200);
				// postData.append('callback',data.callbackBody)
				postData.append("signature", data.signature);
				postData.append("file", data.file);

				http.post(url, postData);
			},

			async handleBatchUpload(fileList, policyData) {
				if (fileList.length == 0) return;
				const filterFileList = fileList.filter((item) => !!item.file);
				const result = [];
				const {
					policy,
					callback,
					accessid,
					signature,
					dir
				} = policyData;
				const {
					callbackBody
				} = JSON.parse(
					CryptoJS.enc.Base64.parse(callback).toString(CryptoJS.enc.Utf8)
				);
				for (let i = 0; i < filterFileList.length; i++) {
					const {
						file
					} = filterFileList[i];
					const param = {
						url: uploadURL,
						name: file.name,
						dir,
						policy,
						accessid,
						signature,
						callbackBody,
						file,
					};

					result.push(await this.uploadFile(param));
				}
				return result;
			},

			async checkStorageResult(fileList) {
				if (fileList.length === 0) return true;
				const filterFileList = fileList.filter((item) => !!item.file);
				const result = [];
				for (let i = 0; i < filterFileList.length; i++) {
					const {
						file
					} = filterFileList[i];
					const {
						size,
						name
					} = file;
					const ext = name.split(".")[name.split(".").length - 1];
					const data = {
						size,
						ext,
						type: "img",
					};

					const code = await this.checkStorageSpace(data);
					result.push(code);
				}

				console.log(result, "result");

				return result.every((item) => item == 10000);
			},
			onEditorBlur(quill) {
				console.log("editor blur!", quill);
				const ruleBox = document.querySelector(".ruleBox");
				const container = document.querySelector(".ql-container");
				const snow = document.querySelector(".ql-snow");
				let text = quill.container.firstChild.innerText.replace(/\s+/g, "");
				if (text == "" && this.type === "edit") {
					// ruleBox.style.display = "block";
					container.style.border = "1px solid red";
					snow.style.border = "1px solid red";
					container.style.borderTop = "0";
				} else {
					this.content = quill.container.firstChild.innerHTML;
					// ruleBox.style.display = "none";
					container.style.border = "1px solid #ccc";
					snow.style.border = "1px solid #ccc";
					container.style.borderTop = "0";
				}
				console.log(quill.container.firstChild.innerText, "标签"); //获得html格式文本,岂不美哉
				console.log(this.content, quill, "标签1"); //获得html格式文本,岂不美哉
			},
			onEditorFocus(quill) {
				console.log("editor focus!", quill);
				const ruleBox = document.querySelector(".ruleBox");
				const container = document.querySelector(".ql-container");
				const snow = document.querySelector(".ql-snow");
				if (this.type === "view") {
					quill.enable(false);
				} else {
					quill.enable(true);
					//  ruleBox.style.display = "none";
					container.style.border = "1px solid #ccc";
					snow.style.border = "1px solid #ccc";
					container.style.borderTop = "0";
				}
			},
			onEditorReady(quill) {
				console.log("editor ready!", quill);
			},
			onEditorChange({
				quill,
				html,
				text
			}) {
				// console.log("editor change!", quill, html, text);
				const ruleBox = document.querySelector(".ruleBox");
				const container = document.querySelector(".ql-container");
				const snow = document.querySelector(".ql-snow");
				let texts = text.replace(/\s+/g, "");
				if (text == "" && this.type === "edit") {
					// ruleBox.style.display = "block";
					container.style.border = "1px solid red";
					snow.style.border = "1px solid red";
					container.style.borderTop = "0";
				} else {
					this.content = quill.container.firstChild.innerHTML;
					// ruleBox.style.display = "none";
					container.style.border = "1px solid #ccc";
					snow.style.border = "1px solid #ccc";
					container.style.borderTop = "0";
				}
				console.log("富文本内容", html);
			},
			quillFn() {
				const ruleBox = document.querySelector(".ruleBox");
				const container = document.querySelector(".ql-container");
				const snow = document.querySelector(".ql-snow");
				ruleBox.style.display = "none";
				container.style.border = "1px solid #ccc";
				snow.style.border = "1px solid #ccc";
				container.style.borderTop = "0";
			},
		},
	};
</script>

<style lang="scss" scoped>
	.form {
		padding: 10px;
	}

	.quill-editor {
		// min-width: 100px;
	}

	// ::v-deep .van-field__label{
	//   width: unset;
	// }
	// ::v-deep .ql-toolbar.ql-snow .ql-formats{
	//   margin-right: 0!important;
	// }
	::v-deep .van-cell {
		margin-top: 2px;
	}

	.quillBox {
		position: relative;
	}

	.ruleBox {
		position: absolute;
		top: 0;
		left: 0;
		display: none;
		border: 1px solid red;
		// background-color: red;
		width: 100%;
		height: 100%;
	}

	.view ::v-deep .ql-container {
		height: 100%;
	}

	::v-deep .ql-container {
		height: calc(100% - 90px);
	}

	.noneBox {
		position: absolute;
		top: 0;
		left: 0;
		display: none;
		border: 1px solid red;
		// background-color: red;
		width: 100%;
		height: 100%;
	}

	.view ::v-deep .ql-toolbar {
		display: none;
	}

	.view ::v-deep .ql-toolbar.ql-snow+.ql-container.ql-snow {
		border-top: 1px solid #ccc;
	}
</style>
